﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows;

namespace AccumulateApp.Helper
{
    public class CommonHelper
    {
        public static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            // Get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);

            // We've reached the end of the tree
            if (parentObject == null) return null;

            // If the parent is the correct type, cast and return it
            T parent = parentObject as T;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                // Otherwise, repeat with the new parent object
                return FindVisualParent<T>(parentObject);
            }
        }


        public static T ReadJsonFile<T>(string path)
        {
            if (File.Exists(path))
            {
                string json = File.ReadAllText(path);
                return JsonConvert.DeserializeObject<T>(json);
            }

            return default(T);
        }

        public static void WriteJsonFile<T>(string path, T t)
        {
            string json = JsonConvert.SerializeObject(t);
            File.WriteAllText(path, json);
        }

        public static string GetAppDataPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AccumulateApp";
        }

        public static void WriteToolFile<T>(string path, T t, JsonSerializerSettings settings)
        {
            File.WriteAllText(path, JsonConvert.SerializeObject(t, settings));
        }

    }
}
